#!/usr/bin/env python

#					 Copyright 2010 Morris Blackham
#
#
#	  This program is free software: you can redistribute it and/or modify
#	  it under the terms of the GNU General Public License as published by
#	  the Free Software Foundation, either version 3 of the License, or
#	  (at your option) any later version.
#
#	  This program is distributed in the hope that it will be useful,
#	  but WITHOUT ANY WARRANTY; without even the implied warranty of
#	  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	  GNU General Public License for more details.
#
#	  You should have received a copy of the GNU General Public License
#	  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import commands

httpconf = "/etc/apache2/httpd.conf"


def getuser():
	global passfile
	passfile = raw_input("Enter path to Apache password file (do not put under htdoc dir): ")
	user = raw_input("Enter FBC admin ID: ")
	pwd = raw_input("Enter admin password: ")

	if os.path.isfile(passfile):
		cmd = ("/usr/bin/htpasswd2 -b " + passfile + " " + user + " " + pwd)
	else:
		cmd = ("/usr/bin/htpasswd2 -c -b " + passfile + " " + user + " " + pwd)
 
	retcode = commands.getstatusoutput(cmd)
	if retcode < 0:
		print "Terminated signal", -retcode
	else:
		print "Ok", retcode 
	return(passfile)


def writefile(passfile):
	y = open(httpconf,'a')
	lines = ["<Location /fbc>\n",
	"	AuthType Basic\n",
	"	AuthName \"Authentication Required\"\n",
	"   AuthUserFile \"" + passfile + "\"\n",
	"	Require valid-user\n",
	"</Location>\n"]
	y.writelines(lines)
	y.close()

def restart():
	cmd = "/etc/init.d/apache2 restart"
	retcode = commands.getstatusoutput(cmd)

for line in open("/etc/sysconfig/apache2","r"):
	if "APACHE_MODULES" in line:
		if line[0] == "#":
			pass
		else:
			if "auth_basic" in line:
				getuser()
				writefile(passfile)	
				restart()				

